/**
 * @file DrawBoard.as
 *
 * @author db0@qq.com
 * @version 1.0.1
 * @date 2017-08-23

example:
var drawBoard:DrawBoard = new DrawBoard();
drawBoard.init();
drawBoard.x = 100;
drawBoard.y = 100;
addChild(drawBoard);
 */
package
{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class DrawBoard extends Sprite
	{
		public var shape:Shape = new Shape();
		private var ww:int;
		private var hh:int;

		public function DrawBoard()
		{
			mouseChildren = false;
			init();

			if (stage) addevents(null);
			else addEventListener(Event.ADDED_TO_STAGE, addevents);
		}

		public function init(w:int = 830, h:int = 546):void
		{
			ww = w;
			hh = h;
			addChild(shape);
			clear();
		}

		private function addevents(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, addevents);
			addEventListener(MouseEvent.MOUSE_DOWN, events);
			addEventListener(MouseEvent.MOUSE_UP, events);
			addEventListener(MouseEvent.MOUSE_OUT, events);
			addEventListener(MouseEvent.MOUSE_MOVE, events);
			//addEventListener(MouseEvent.MOUSE_OVER,events);
		}

		public function clear():void
		{
			with (shape.graphics)
			{
				clear();
				beginFill(0xffffff, 0.0);
				drawRect(0, 0, ww, hh);
				endFill();
				lineStyle(lineSize, lineColor);
			}
			_hasDrawed = false;
		}
		private var _lineSize:int=10;
		private var _lineColor:uint=0xff000000;
		public function set lineSize(i:int):void
		{
			_lineSize = i;
			if(shape)
				shape.graphics.lineStyle(lineSize, lineColor);
		}
		public function set lineColor(i:uint):void
		{
			_lineColor= i;
			if(shape)
				shape.graphics.lineStyle(lineSize, lineColor);
		}
		public function get lineSize():int
		{
			return _lineSize;
		}
		public function get lineColor():uint
		{
			return _lineColor;
		}

		private var isDrawing:Boolean = false;
		private var _hasDrawed:Boolean = false;

		public function get hasDrawed():Boolean
		{
			return _hasDrawed;
		}

		private function events(e:MouseEvent):void
		{
			if (shape.x < mouseX && mouseX < shape.x + shape.width && shape.y < mouseY && mouseY < shape.y + shape.height)
			{
			}
			else
			{
				isDrawing = false;
				return;
			}
			//logs.adds(e.type);
			switch (e.type)
			{
				case MouseEvent.MOUSE_DOWN: 
				case MouseEvent.MOUSE_OVER: 
					shape.graphics.moveTo(mouseX - 1, mouseY - 1);
					shape.graphics.lineTo(mouseX, mouseY);
					isDrawing = true;
					_hasDrawed = true;
					break;
				case MouseEvent.MOUSE_UP: 
				case MouseEvent.MOUSE_OUT: 
					isDrawing = false;
					break;
				case MouseEvent.MOUSE_MOVE: 
					if (!isDrawing)
					{
						shape.graphics.moveTo(mouseX, mouseY);
						return;
					}
					shape.graphics.lineTo(mouseX, mouseY);
					break;
			}
		}
	}
}
